import React from 'react'
import PropTypes from "prop-types";
import {serialize} from '../utils/http'

/**
 * Http高阶组件，用于装饰需要http请求的组件
 * @param WrappedComponent 被装饰的组件
 * @param options 请求参数
 * @param callback 返回结果用于被包装组件的props
 * @param dflt 默认显示
 * @returns {{new(*=): {componentDidMount(): void, render(): (undefined|void)}, prototype: {componentDidMount(): void, render(): (undefined|void)}}}
 * @constructor
 */
const Http = (options, callback, dflt) =>
    WrappedComponent =>
    class extends React.Component{
        constructor(props) {
            super(props)
            this.state = {
                isLoaded:false,
                data:{}
            }
        }
        http() {
            if(!options.url)
                throw 'Http组件没有指定URL'
            let url = options.url, method = options.method || 'GET',
                data = options.data || {}, header = options.header || {},
                propsData = this.props.propsData || {}
            let params = Object.assign({}, data, propsData)
            fetch(url + '?' + serialize(data), {
                method: method,
                headers: header,
                dataType: 'json'
            }).then(response => response.json())
                .then(json => {
                    let res = callback(json)
                    this.setState({
                        isLoaded: true,
                        data: res
                    })
                }).catch(err => {
                throw err
            })
        }
        componentDidMount() {
            this.http()
        }
        getHttpData() {
            return this.state.data
        }
        reload() {
            this.setState({
                isLoaded: false
            })
            this.http()
        }
        render() {
            if(!this.state.isLoaded)
                return dflt?dflt:null
            return <WrappedComponent {...this.state.data} {...this.props} reset={this.reload}/>

        }
    }
    export default Http
